var ImagePreview = function ($) {
	function ImagePreview() {
	}


}(jQuery);

var App = function ($) {

	function App() {
	}

	App.template = {
		bool: function (data, type, row, meta) {
			return data == true
					? '<i class="fa fa-check-square-o"></i>'
					: '<i class="fa fa-square-o"></i>';
		},

		check: function (data, type, row, meta) {
			return '<label class="custom-control custom-checkbox">'
					+ '	<input type="checkbox" class="custom-control-input">'
					+ '	<span class="custom-control-indicator"></span>'
					+ '</label>'
		}
	};

	/**
	 * 获取 target 上的 data-url 属性，避免在 js 中写入动态请求路径
	 * @param target 目标选择器
	 */
	App.dataUrl = function (target) {
		return target ? $(target).attr('data-url') : '';
	};

	App.format = function format() {
		var args = arguments;
		var str = args[0];
		return str.replace(/\{(\d+)\}/g, function (s, i) {
			return args[parseInt(i) + 1];
		});
	};

	App.splitWithoutEmpty = function (str) {
		var result = [];
		if (typeof str != 'string') {
			return result;
		}

		var temp = str.split(' ');
		for (var i = 0, j = temp.length; i < j; i++) {
			if (temp[i] != '') {
				result.push(temp[i]);
			}
		}
		return result;
	};

	App.form2json = function (selector) {
		var kvArray = $(selector).serializeArray();
		var result = {};

		function loop(hierarchy, index, object, value) {
			var name = hierarchy[index];
			if (hierarchy.length === index + 1) {
				object[name] = value;
			} else {
				if (!object[name]) {
					object[name] = {};
				}
				loop(hierarchy, index + 1, object[name], value);
			}
		}

		$.map(kvArray, function (n, i) {
			// loop(n['name'].split('.'), 0, result, n['value']);
			var k = n['name'];
			var v = n['value'];
			if (result[k] === undefined) {
				result[k] = v;
			} else {
				var temp = [result[k]];
				temp.push(v);
				result[k] = temp;
			}
		});

		return result;
	};

	App.handleAjax = function (data, successHandler, failureHandler) {
		if (data) {
			if (data.type === 'SUCCESS') {
				successHandler && successHandler(data);
			} else if (data.type === 'FAILURE') {
				failureHandler && failureHandler(data);
			} else if (data.type === 'REDIRECT') {
				data.url && (window.location.href = data.url);
			}
		}
	};

	/**
	 * 从子页面调用添加标签页的方法，如果顶级页面没有 openTab 方法，则另开浏览器 tab 浏览。
	 * @param options
	 * @returns {boolean}
	 */
	App.openTab = function (options) {
		if (top.$().dynamicTab()) {
			if (top.openTab) {
				var type = typeof  top.openTab;
				if (type === 'function') {
					top.openTab(options);
					return false;
				}
			}
		}
		window.open(options.url);
		return false;
	};

	App.initDatetimePicker = function () {
		$('[data-type="datetime-picker"]').each(function () {
			var el = $(this).find('input');
			var maskInput = el.data('maskInput') || false;
			var pickDate = el.data('pickDate') === undefined ? true : el.data('pickDate');
			var pickTime = el.data('pickTime') === undefined ? true : el.data('pickTime');
			var pick12HourFormat = el.data('pick12HourFormat') || false;
			var pickSeconds = el.data('pickSeconds') === undefined ? true : el.data('pickSeconds');
			var startDate = el.data('startDate') || -Infinity;
			var endDate = el.data('endDate') || Infinity;

			$(this).datetimepicker({
				maskInput: maskInput,
				pickDate: pickDate,
				pickTime: pickTime,
				pick12HourFormat: pick12HourFormat,
				pickSeconds: pickSeconds,
				startDate: startDate,
				endDate: endDate
			});
		});
	};

	App.notifyCenter = function (message, type, element) {
		var o = {message: message}, s = {type: 'info'}, temp = {element: 'body'};
		if (type !== undefined) {
			s = {type: type.toLowerCase()};
		}
		if (element !== undefined) {
			temp = {element: element};
		}

		s = $.extend({}, s, temp);
		App.notify(o, s);
	};

	App.notify = function (opt, set) {
		var options = $.extend({}, {
			icon: 'fa fa-info-circle',
			title: '',
			message: '',
			url: 'javascript:',
			target: '_blank'
		}, opt);
		var settings = $.extend(true, {}, {
			element: 'body',
			position: null,
			type: "info",
			allow_dismiss: true,
			newest_on_top: true,
			showProgressbar: false,
			placement: {
				from: "top",
				align: "center"
			},
			offset: 0,
			spacing: 10,
			z_index: 1031,
			delay: 5000,
			timer: 1000,
			url_target: '_blank',
			mouse_over: null,
			animate: {
				enter: 'animated fadeInDown',
				exit: 'animated fadeOutUp'
			},
			onShow: null,
			onShown: null,
			onClose: null,
			onClosed: null,
			icon_type: 'class',
			template: '<div data-notify="container" class="col-12 col-md-9 alert alert-{0}" role="alert">' +
			'<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
			'<span data-notify="icon"></span> ' +
			'<span data-notify="title">{1}</span> ' +
			'<span data-notify="message">{2}</span>' +
			'<div class="progress" data-notify="progressbar">' +
			'<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
			'</div>' +
			'<a href="{3}" target="{4}" data-notify="url"></a>' +
			'</div>'
		}, set);
		return $.notify(options, settings);
	};

	App.alertProcess = function (title, text) {
//		var temp = 0;
//		setInterval(function () {
//			var text = text;
//			for (var i = 0, t = temp % 7; i < t; i++) {
//				text += '.';
//			}

		swal({
			title: title,
			text: text,
			showConfirmButton: false
		});
//			temp++;
//		}, 1000);
	};

	App.alert = swal;
	App.alertInfo = function (title, text, ext) {
		swal($.extend(true, {text: text, title: title, icon: 'info'}, ext));
	};
	App.alertSuccess = function (title, text, ext) {
		swal($.extend(true, {text: text, title: title, icon: 'success'}, ext));
	};
	App.alertError = function (title, text, ext) {
		swal($.extend(true, {text: text, title: title, icon: 'error'}, ext));
	};

	App.handleNotify = function (list) {
		if (list) {
			for (var i = 0; i < list.length; i++) {
				var temp = list[i];
				if (temp.type === 'NOTIFY') {
					var m = $.extend(true, {}, temp.extra, {type: temp.level.toLowerCase()});
					App.notify(temp, m);
				}
				if (temp.type === 'ALERT') {
					var m = {text: temp.message, title: temp.title};
					var l = temp.level.toLowerCase();
					if (l === 'danger') {
						l = 'error';
					}
					m.icon = l;

					$.extend(true, m, temp.extra);
					swal(m);
				}
			}
		}
	};

	/** 扩展为 jquery 全局方法 */
	var jqExtend = {
		format: App.format,
		splitWithoutEmpty: App.splitWithoutEmpty
	};

	$.extend(jqExtend);

	return App;
}(jQuery);

$.validator && $.validator.setDefaults({
	errorElement: 'div',
	errorClass: 'text-danger form-control-feedback',
//	errorPlacement: function (error, element) {
//		error.appendTo(element.parent("td").next("td"));
//	}
});

/**
 * 全局执行方法
 */
$(function () {
	$('.scrollable').slimScroll({
		height: 'auto',
		alwaysVisible: true
	});
	App.initDatetimePicker();

	hookAjax({
		onload: function (xhr) {
			try {
				var json = JSOG.parse(xhr.response);
				if (json.status === 901 && (json.redirectUrl && json.redirectUrl.length > 0)) {
					top.location.href = json.redirectUrl;
				}
			} catch (ex) {
			}
		}
	});
});